package com.wxp.demo09.screen;

import android.app.PictureInPictureParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Rational;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.wxp.demo09.R;
import com.wxp.demo09.util.LogUtils;

/**
 * 3.3 回到桌面与切换到任务列表
 */
public class ReturnDesktopActivity extends AppCompatActivity {

    private DesktopReceiver desktopReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_return_desktop);
        this.setTitle("3.3 回到桌面与切换到任务列表");

        desktopReceiver = new DesktopReceiver();
        //定义回到桌面过滤器
        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        this.registerReceiver(desktopReceiver, filter, Context.RECEIVER_EXPORTED);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(desktopReceiver);
    }

    /**
     * 在进入画中画模式或退出画中画模式时触发
     */
    @Override
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
        if (isInPictureInPictureMode) {
            LogUtils.debug("进入画中画模式");
        } else {
            LogUtils.debug("退出画中画模式");
        }
    }

    /**
     * 定义一个返回到桌面的广播接收器
     */
    private class DesktopReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //判断是否回到桌面
            if (intent != null && Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
                String reason = intent.getStringExtra("reason");
                if (!TextUtils.isEmpty(reason)
                        && (reason.equals("homekey") || reason.equals("recentapps"))
                ) {
                    // Android 8.0开始才提供画中画模式
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                            && !isInPictureInPictureMode()) {
                        // 创建画中画模式的参数构建器
                        PictureInPictureParams.Builder builder = new PictureInPictureParams.Builder();
                        // 设置宽高比例值，第一个参数表示分子，第二个参数表示分母
                        // 下面的10/5=2，表示画中画窗口的宽度是高度的两倍
                        // 设置画中画窗口的宽高比例
                        Rational ratio = new Rational(10, 5);
                        builder.setAspectRatio(ratio);
                        // 进入画中画模式
                        enterPictureInPictureMode(builder.build());
                    }
                }
            }
        }
    }

}